package com.board.entity;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static String sect="ksdjnfkshifhhfihkfhsfhshfkshfklshfuhsfh";//加密的密钥

    //登录后生成的token
    public static String createToken(Map<String,Object> body, Integer mil){
        Key key = Keys.hmacShaKeyFor(sect.getBytes());
        return Jwts.builder()
                .setClaims(body) //token中的主体存放的内容
                .setExpiration(new Date(System.currentTimeMillis()+mil*60*1000)) //设置token有效期
                .signWith(key) //设置签名
                .compact();
    }

    //校验解析token
    public static Claims parseToken(String token){
        Key key = Keys.hmacShaKeyFor(sect.getBytes());
        return Jwts.parserBuilder().setSigningKey(key)
                .build().parseClaimsJws(token).getBody();
    }

    //获取jwt中存储的数据
    public static Object getData(String token,String key){
        Claims claims = parseToken(token);
        return claims.get(key);
    }
}
